package com.zzzy.interceptor;

import com.zzzy.config.DynamicDataSourceContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DynamicDataSourceInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {


        System.out.println("httpServletRequest.getRequestURI() :" + httpServletRequest.getRequestURI());
        Object tenent = httpServletRequest.getSession().getAttribute("tenent");
        if(null != tenent) {
            String dbid = tenent.toString();
            logger.debug("dbid:"+dbid);
            DynamicDataSourceContextHolder.setDataSource(dbid);
        }
        return true;
        //return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
